import { ElMessage } from 'element-plus';
// import {useRouter} from "vue-router";
import {router} from '../router/index.js'
// const router = useRouter()
// 退出登录
const loginOut = () => {
    localStorage.clear();
    sessionStorage.clear();
    router.replace({path: '/'})
}

// const router = useRouter();
export const setInterceptors = (axiosInstance) => {
    // 请求拦截
    axiosInstance.interceptors.request.use(request => {
        let tokenValue = sessionStorage.getItem('tokenValue');
        let tokenName = sessionStorage.getItem('tokenName');
        let TOKEN = 'Uexpo '+ tokenValue;
        request['headers'][tokenName] = TOKEN
        return request;
    }, error => Promise.reject(error));

    // 响应拦截
    axiosInstance.interceptors.response.use(response => {
        // console.log(response);
        // let msg = response.data.msg;
        // if(msg.indexOf('无效：') > -1) {
        //     ElMessage({ message: response.data.msg||'token失效，请重新登录', type: 'warning'});
        //     loginOut()
        // }
        let responseCode = response.data.code;
        switch (responseCode) {
            case 403:{
                ElMessage({ message: response.data.msg||'token失效，请重新登录', type: 'warning'});
                loginOut();
                break;
            }
        }
        return response;
    }, error => {
        console.log(error);
        return Promise.reject(error.response);
    })
};